# # 作者信息：Katharina Löffler (2022)，卡尔斯鲁厄理工学院，使用MIT许可证
# """
# Author: Katharina Löffler (2022), Karlsruhe Institute of Technology
# Licensed under MIT License
# """

# # 导入必要的库
# import re
# import shutil
# from pathlib import Path

# import numpy as np
# import pandas as pd
# from tifffile import imread, imsave
# import sys
# import os
# sys.path.append(r'D:\CodeRode\project\EmbedTrack-master')
# # 从embedtrack工具包导入路径和索引处理函数
# from embedtrack.utils.utils import (
#     collect_leaf_paths,
#     collect_paths,
#     get_indices_pandas,
# )
# import os
# from embedtrack.datasets.generate_crops import process


# # 复制并重命名数据函数
# def copy_and_rename_data(
#     raw_data_dir, result_dir, keep_st=True, sub_dir_names=["01", "02"]
# ):
#     """
#     复制细胞跟踪挑战(CTC)数据集，并保留ST或GT注释掩码。
#     参数:
#         raw_data_dir (Path): 原始CTC数据集存储路径
#         result_dir (Path): 修改后的数据集副本将存储的路径
#         keep_st (bool): 使用ST(silver truth)或GT(gold truth)注释
#         sub_dir_names (list): 要复制的图像序列列表
#     """
#     result_dir = result_dir
#     # 获取所有子目录
#     sub_directories = [
#         element
#         for element in os.listdir(raw_data_dir)
#         if os.path.isdir(raw_data_dir / element)
#     ]
#     # 复制相关数据
#     for sub_dir in sub_directories:
#         copy_sub_dir = (
#             sub_dir.isnumeric()
#             or sub_dir == (sub_dir.split("_")[0] + "_ST")
#             or sub_dir == (sub_dir.split("_")[0] + "_GT")
#         )
#         if copy_sub_dir:
#             shutil.copytree(raw_data_dir / sub_dir, result_dir / sub_dir)
    
#     # 确定要删除的目录类型
#     if keep_st:
#         rm_dir = "_GT"
#     else:
#         rm_dir = "_ST"

#     # 筛选要保留的目录
#     keep_dirs = [sub_dir for sub_dir in os.listdir(result_dir) if rm_dir not in sub_dir]
#     img_dirs = [sub_d for sub_d in keep_dirs if sub_d.isnumeric()]
#     mask_dirs = [sub_d for sub_d in keep_dirs if not sub_d.isnumeric()]
#     # 排序子目录以避免shutil.move问题
#     keep_dirs = img_dirs + mask_dirs

#     # 为每个序列创建目录
#     for sub_dir_name in sub_dir_names:
#         if not os.path.exists(result_dir / sub_dir_name):
#             os.mkdir(result_dir / sub_dir_name)

#     # 处理每个保留的目录
#     for sub_dir in keep_dirs:
#         sub_dir_name = sub_dir.split("_")[0]
#         assert sub_dir_name.isnumeric(), f"未知的目录命名 {sub_dir}"
#         if sub_dir.isnumeric():
#             dir_name = "images"
#         else:
#             dir_name = "masks"
#             # 如果保留ST，则需要将ST分割注释与GT谱系注释融合
#             if keep_st:
#                 gt_dir = sub_dir.split("_")[0] + "_GT"
#                 generate_st_gt_lineage(
#                     result_dir / sub_dir / "SEG", result_dir / gt_dir / "TRA"
#                 )
#             else:
#                 # 如果保留GT，则删除除TRA外的所有子目录
#                 sub_sub_dir = [
#                     element
#                     for element in os.listdir(result_dir / sub_dir)
#                     if os.path.isdir(result_dir / sub_dir / element)
#                 ]
#                 for d in sub_sub_dir:
#                     if d != "TRA":
#                         shutil.rmtree(result_dir / sub_dir / d)
        
#         # 移动文件到新的目录结构
#         data_path = result_dir / sub_dir_name / dir_name
#         os.makedirs(str(data_path), exist_ok=True)
#         try:
#             shutil.move(str(result_dir / sub_dir), str(data_path))
#         except shutil.Error:
#             # 处理移动过程中的错误
#             temp = result_dir / "temp"
#             os.makedirs(str(temp), exist_ok=True)
#             shutil.move(str(result_dir / sub_dir), str(temp))
#             shutil.move(str(temp), str(data_path))

#         # 整理文件结构，将所有文件移到顶层目录
#         all_files = [
#             data_path / d_path / file
#             for d_path in collect_paths(data_path)
#             for file in os.listdir(d_path)
#         ]
#         sub_sub_dir = [
#             data_path / element
#             for element in os.listdir(data_path)
#             if os.path.isdir(data_path / element)
#         ]
#         for file in all_files:
#             shutil.move(file, data_path / file.name)
#         for directory in sub_sub_dir:
#             shutil.rmtree(directory)

#     # 重命名数据文件
#     data_paths = [collect_leaf_paths(result_dir / sub_dir) for sub_dir in sub_dir_names]
#     data_paths = [element for path_list in data_paths for element in path_list]
#     for sub_dir in data_paths:
#         for file in os.listdir(sub_dir):
#             if file.endswith(".tif"):
#                 # 根据不同前缀规则重命名文件
#                 if file.startswith("t"):
#                     new_name = file[1:]
#                 elif file.startswith("mask"):
#                     new_name = file.replace("mask", "")
#                 elif file.startswith("man_track"):
#                     new_name = file.replace("man_track", "")
#                 elif file.startswith("man_seg"):
#                     new_name = file.replace("man_seg", "")
#                 else:
#                     raise AssertionError(file)
#                 shutil.move(str(sub_dir / file), str(sub_dir / new_name))
#             # 处理谱系文件
#             if file.endswith(".txt"):
#                 file_name = "track.txt"
#                 shutil.move(str(sub_dir / file), str(sub_dir.parent / file_name))
                
#     # 删除不需要的目录
#     for element in os.listdir(result_dir):
#         if os.path.isdir(result_dir / element):
#             if element not in sub_dir_names:
#                 shutil.rmtree(result_dir / element)


# # 生成ST-GT融合谱系
# def generate_st_gt_lineage(st_seg_path, gt_track_path, res_path=None):
#     """
#     使用ST分割和GT跟踪注释创建注释数据集。
#     参数:
#         st_seg_path (string): ST注释路径
#         gt_track_path (string): GT跟踪注释路径
#         res_path (string): 存储融合注释的路径
#     """
#     if res_path is None:
#         res_path = st_seg_path

#     # 获取ST分割文件和GT跟踪文件，并按时间点索引
#     st_seg_files = {
#         int(re.findall("\d+", file)[0]): os.path.join(st_seg_path, file)
#         for file in os.listdir(st_seg_path)
#         if file.endswith(".tif")
#     }
#     gt_track_files = {
#         int(re.findall("\d+", file)[0]): os.path.join(gt_track_path, file)
#         for file in os.listdir(gt_track_path)
#         if file.endswith(".tif")
#     }
#     # 获取谱系文件
#     lineage_file = [
#         os.path.join(gt_track_path, file)
#         for file in os.listdir(gt_track_path)
#         if file.endswith(".txt")
#     ][0]

#     # 读取GT谱系信息
#     gt_lineage = pd.read_csv(
#         lineage_file,
#         delimiter=" ",
#         header=None,
#         names=["cell_id", "t_start", "t_end", "predecessor"],
#     )
#     gt_lineage = gt_lineage.set_index("cell_id")
#     st_lineage = {}  # 存储ST谱系: cellid: (t_start, t_end, successor)

#     # 处理时间点限制
#     t_max = gt_lineage["t_end"].max()
#     st_seg_files = {
#         time_point: img_path
#         for time_point, img_path in st_seg_files.items()
#         if time_point <= t_max
#     }
    
#     # 遍历每个时间点，融合ST分割和GT跟踪
#     for time in sorted(st_seg_files.keys()):
#         st_seg_mask = imread(st_seg_files[time])
#         gt_track_mask = imread(gt_track_files[time])
#         fused_mask = np.zeros_like(gt_track_mask)
#         seg_mask_indices = get_indices_pandas(st_seg_mask)
        
#         # 处理每个分割掩码的索引
#         for mask_id, mask_indices in seg_mask_indices.items():
#             gt_obj_ids = np.unique(gt_track_mask[mask_indices])
#             gt_obj_ids = gt_obj_ids[gt_obj_ids > 0]
#             # 如果ST掩码映射到单个GT对象
#             if len(gt_obj_ids) == 1:
#                 gt_id = gt_obj_ids[0]
#                 fused_mask[mask_indices] = gt_id
#                 # 更新或创建谱系信息
#                 if gt_id not in st_lineage:
#                     predecessor = gt_lineage.loc[gt_id]["predecessor"]
#                     # 检查前任是否已经添加到谱系中
#                     if predecessor in st_lineage:
#                         st_lineage[gt_id] = [time, time, predecessor]
#                     else:
#                         st_lineage[gt_id] = [time, time, 0]
#                 else:
#                     st_lineage[gt_id][1] = time
                
#         # 保存融合掩码
#         file_name = os.path.split(st_seg_files[time])[1]
#         if not os.path.exists(res_path):
#             os.makedirs(res_path)
#         imsave(os.path.join(res_path, file_name), fused_mask, compression=("ZSTD", 1))
    
#     # 保存ST谱系信息
#     df = pd.DataFrame.from_dict(st_lineage, orient="index")
#     df = df.reset_index().sort_values("index")
#     df.to_csv(
#         os.path.join(res_path, "res_track.txt"), sep=" ", index=False, header=False
#     )


# # 训练验证集分割函数
# def train_val_split(result_path, sub_dir_names, val_split, original_data_root=None, center_type="medoid"):
#     """
#     通过从每个图像序列中分割固定百分比进行验证，将数据集分为训练/验证。
#     参数:
#         result_path (Path): 数据集路径
#         sub_dir_names (list): 用于训练/验证的图像序列列表
#         val_split (float): 从每个图像序列分割用于验证的图像+掩码的比例；
#                             所有剩余的图像+掩码用于训练
#         original_data_root (Path): 原始数据集的根目录
#         center_type (str): 中心类型，默认为"medoid"
#     """
#     for sub_dir in sub_dir_names:
#         data_path_train = result_path / "train" / sub_dir
#         data_path_val = result_path / "val" / sub_dir
#         os.makedirs(str(data_path_train / "images"), exist_ok=True)
#         os.makedirs(str(data_path_train / "masks"), exist_ok=True)
#         os.makedirs(str(data_path_val / "images"), exist_ok=True)
#         os.makedirs(str(data_path_val / "masks"), exist_ok=True)
#         # 获取所有图片和mask文件名
#         images_dir = result_path / sub_dir / "images"
#         masks_dir = result_path / sub_dir / "masks"
#         image_files = sorted(os.listdir(str(images_dir))) if images_dir.exists() else []
#         mask_files = sorted(os.listdir(str(masks_dir))) if masks_dir.exists() else []
#         # 只用images文件名做划分，假设images和masks一一对应
#         n_val = int(len(image_files) * val_split)
#         val_image_files = set(image_files[:n_val])
#         for img_file in image_files:
#             src_img = images_dir / img_file
#             src_mask = masks_dir / img_file.replace("t", "mask", 1)  # t000.tif -> mask000.tif
#             if img_file in val_image_files:
#                 dst_img = data_path_val / "images" / img_file
#                 dst_mask = data_path_val / "masks" / src_mask.name
#             else:
#                 dst_img = data_path_train / "images" / img_file
#                 dst_mask = data_path_train / "masks" / src_mask.name
#             shutil.move(str(src_img), str(dst_img))
#             if src_mask.exists():
#                 shutil.move(str(src_mask), str(dst_mask))
#         # 确保train/val目录本身存在
#         os.makedirs(str(data_path_train), exist_ok=True)
#         os.makedirs(str(data_path_val), exist_ok=True)
#         # track.txt查找路径修正
#         if original_data_root is not None:
#             src_track = original_data_root / sub_dir / "track.txt"
#         else:
#             src_track = result_path / sub_dir / "track.txt"
#         dst_track_train = data_path_train / "track.txt"
#         dst_track_val = data_path_val / "track.txt"
#         print(f"[DEBUG] 拷贝track.txt: {src_track} -> {dst_track_train}, {dst_track_val}")
#         if src_track.exists():
#             shutil.copy(str(src_track), str(dst_track_train))
#             shutil.copy(str(src_track), str(dst_track_val))
#         else:
#             print(f"[WARNING] 源track.txt不存在: {src_track}")
#         # center-medoid目录同步
#         center_dir = result_path / sub_dir / f"center-{center_type}"
#         center_train = data_path_train / f"center-{center_type}"
#         center_val = data_path_val / f"center-{center_type}"
#         os.makedirs(str(center_train), exist_ok=True)
#         os.makedirs(str(center_val), exist_ok=True)
#         for img_file in image_files:
#             src_center = center_dir / img_file.replace("t", "center", 1)
#             print(f"[DEBUG] center-medoid: src_center={src_center}, exists={src_center.exists()}")
#             if img_file in val_image_files:
#                 dst_center = center_val / src_center.name
#             else:
#                 dst_center = center_train / src_center.name
#             if src_center.exists():
#                 shutil.move(str(src_center), str(dst_center))
#             else:
#                 print(f"[WARNING] center图像不存在: {src_center}")


# # 准备CTC数据的主函数
# def prepare_ctc_data(
#     source_path, result_path, keep_st=True, val_split=0.1, sub_dir_names=["01", "02"]
# ):
#     """
#     复制CTC数据集并准备训练/验证分割。
#     参数:
#         source_path (string): 原始CTC数据集存储路径
#         result_path (string): 准备好的(训练/验证)数据集将存储的路径
#         keep_st (bool): 使用ST(silver truth)或GT(gold truth)注释
#         val_split (float): 从每个图像序列分割用于验证的图像+掩码的比例；
#                            所有剩余的图像+掩码用于训练
#         sub_dir_names (list): 用于训练/验证的图像序列列表
#     """
#     source_path = Path(source_path)
#     result_path = Path(result_path)
#     result_path = result_path / source_path.name
#     # 复制并重命名数据
#     copy_and_rename_data(source_path, result_path, keep_st, sub_dir_names)
#     # 分割训练和验证集
#     train_val_split(result_path, sub_dir_names, val_split, original_data_root=source_path)
#     # 生成center图像（分别对train和val目录）
#     for split in ["train", "val"]:
#         split_dir = result_path / split
#         if split_dir.exists():
#             generate_all_centers(split_dir, sub_dir_names, center_type="medoid", crop_size=256)


# # 准备CTC地面真值数据
# def prepare_ctc_gt(source_path, result_path, val_split=0.1, sub_dir_names=["01", "02"]):
#     """
#     准备具有相同训练/验证分割的GT CTC数据集
#     参数:
#         source_path (string): 原始CTC数据集存储路径
#         result_path (string): 准备好的(训练/验证)GT数据集将存储的路径
#         val_split (float): 从每个图像序列分割用于验证的图像+掩码的比例；
#                            所有剩余的图像+掩码用于训练
#         sub_dir_names: 用于训练/验证的图像序列列表
#     """
#     # 创建结果目录
#     res_path = os.path.join(result_path, Path(source_path).name, "gt")
#     os.makedirs(os.path.join(res_path, "train"))
#     os.makedirs(os.path.join(res_path, "val"))

#     # 处理每个GT子目录
#     for sub_dir in os.listdir(source_path):
#         if not sub_dir.endswith("_GT"):
#             continue
#         sub_dir_name = sub_dir.split("_")[0]
#         assert sub_dir_name.isnumeric(), f"未知的目录命名 {sub_dir}"
#         if sub_dir_name in sub_dir_names:
#             data_path = Path(os.path.join(res_path, "train", sub_dir))

#             # 复制GT数据
#             shutil.copytree(
#                 os.path.join(source_path, sub_dir),
#                 data_path,
#             )
#             # 分割GT数据
#             split_gt_data(data_path, val_split)


# # 分割谱系文件为训练和验证部分
# def split_lineage_file_train_val(lineage_file, val_split):
#     """
#     将谱系文件分为训练和验证谱系。
#     参数:
#         lineage_file (string): 谱系文件路径
#         val_split (float): 从每个图像序列分割用于验证的图像+掩码的比例；
#                            所有剩余的图像+掩码用于训练
#     """
#     lineage_name = os.path.basename(lineage_file)
#     # 读取完整谱系
#     full_lineage = pd.read_csv(
#         lineage_file,
#         delimiter=" ",
#         header=None,
#         names=["cell_id", "t_start", "t_end", "predecessor"],
#     )
#     # 获取所有时间点
#     time_points = np.arange(
#         full_lineage["t_start"].min(), full_lineage["t_end"].max() + 1
#     )
#     # 计算验证集大小和开始时间点
#     n_val = int(len(time_points) * val_split)
#     t_val_start = time_points[-n_val]

#     # 处理训练集谱系
#     train_lineage = full_lineage.copy()
#     t_train_end = time_points[-n_val - 1]
#     # 筛选训练集数据
#     train_lineage = train_lineage[train_lineage["t_start"] <= t_train_end]
#     # 调整训练集结束时间
#     train_lineage["t_end"] = train_lineage["t_end"].apply(lambda x: min(t_train_end, x))
#     # 保存训练集谱系
#     train_lineage.to_csv(lineage_file, sep=" ", header=False, index=False)

#     # 处理验证集谱系
#     val_lineage = full_lineage.copy()
#     # 筛选验证集数据
#     val_lineage = val_lineage[val_lineage["t_end"] >= t_val_start]
#     # 调整验证集开始时间
#     val_lineage["t_start"] = val_lineage["t_start"].apply(lambda x: max(t_val_start, x))
#     # 获取验证集中的细胞ID
#     cells_val_data = val_lineage["cell_id"].values
#     # 调整前任ID，确保仅引用验证集中的细胞
#     val_lineage["predecessor"] = val_lineage["predecessor"].apply(
#         lambda x: 0 if x not in cells_val_data else x
#     )
#     # 从路径中提取目录结构
#     d_path = Path(lineage_file).parent.parent.parent
#     img_sequence = Path(lineage_file).parent.name
#     # 保存验证集谱系
#     val_lineage.to_csv(
#         os.path.join(str(d_path), "val", img_sequence, lineage_name),
#         sep=" ",
#         header=False,
#         index=False,
#     )


# # 分割GT数据为训练和验证集
# def split_gt_data(res_path, val_split):
#     """
#     将gt(ground truth)数据分为训练/验证数据集。
#     参数:
#         res_path (Path): gt数据集的路径
#         val_split (float): 从每个图像序列分割用于验证的图像+掩码的比例；
#                          所有剩余的图像+掩码用于训练
#     """
#     # 获取跟踪路径
#     tra_path = res_path / "TRA"
#     # 提取并排序时间点
#     time_points = [
#         int(re.findall(r"\d+", mask_file)[0])
#         for mask_file in os.listdir(tra_path)
#         if mask_file.endswith("tif")
#     ]
#     time_points.sort(key=lambda x: x)
#     # 计算验证集大小和开始时间点
#     n_val = int(len(time_points) * val_split)
#     t_val_start = time_points[-n_val]
    
#     # 处理每个GT路径
#     for seg_track_gt_path in collect_leaf_paths(os.path.join(res_path)):
#         # 获取掩码文件并过滤出验证集时间点的文件
#         mask_files = [
#             (int(re.findall(r"\d+", file)[0]), file)
#             for file in os.listdir(seg_track_gt_path)
#             if file.endswith("tif")
#         ]
#         mask_files = filter(lambda x: x[0] >= t_val_start, mask_files)
#         # 构建验证集路径
#         path_parts = Path(seg_track_gt_path).parts
#         val_path = os.path.join(*path_parts[:-3], "val", *path_parts[-2:])
#         if not os.path.exists(val_path):
#             os.makedirs(val_path)
#         # 移动验证集掩码文件
#         for _, mask_file in mask_files:
#             shutil.move(
#                 os.path.join(seg_track_gt_path, mask_file),
#                 os.path.join(val_path, mask_file),
#             )
            
#     # 处理谱系文件
#     lineage_file = os.path.join(tra_path, "man_track.txt")
#     # 读取GT谱系
#     gt_lineage = pd.read_csv(
#         lineage_file,
#         delimiter=" ",
#         header=None,
#         names=["cell_id", "t_start", "t_end", "predecessor"],
#     )

#     # 处理训练集谱系
#     train_lineage = gt_lineage.copy()
#     t_train_end = time_points[-n_val - 1]
#     train_lineage = train_lineage[train_lineage["t_start"] <= t_train_end]
#     train_lineage["t_end"] = train_lineage["t_end"].apply(lambda x: min(t_train_end, x))
#     train_lineage.to_csv(lineage_file, sep=" ", header=False, index=False)

#     # 处理验证集谱系
#     val_lineage = gt_lineage.copy()
#     val_lineage = val_lineage[val_lineage["t_end"] >= t_val_start]
#     val_lineage["t_start"] = val_lineage["t_start"].apply(lambda x: max(t_val_start, x))
#     cells_val_data = val_lineage["cell_id"].values
#     val_lineage["predecessor"] = val_lineage["predecessor"].apply(
#         lambda x: 0 if x not in cells_val_data else x
#     )
#     # 构建验证集谱系文件路径
#     path_parts = Path(lineage_file).parts
#     val_path = os.path.join(*path_parts[:-4], "val", *path_parts[-3:])
#     val_lineage.to_csv(val_path, sep=" ", header=False, index=False)

# # 添加到 prepare_data.py 中的调试代码

# import os
# import shutil
# from pathlib import Path

# def debug_copy_and_rename_data(raw_data_dir, result_dir, keep_st=True, sub_dir_names=["01", "02"]):
#     """
#     带调试信息的数据复制函数
#     """
#     print(f"原始数据目录: {raw_data_dir}")
#     print(f"目标目录: {result_dir}")
#     print(f"保留ST注释: {keep_st}")
#     print(f"处理序列: {sub_dir_names}")
    
#     # 检查原始数据目录存在性
#     if not os.path.exists(raw_data_dir):
#         raise FileNotFoundError(f"原始数据目录不存在: {raw_data_dir}")
    
#     # 列出原始数据目录中的所有子目录
#     sub_directories = [
#         element
#         for element in os.listdir(raw_data_dir)
#         if os.path.isdir(raw_data_dir / element)
#     ]
#     print(f"找到的子目录: {sub_directories}")
    
#     # 复制相关数据
#     for sub_dir in sub_directories:
#         copy_sub_dir = (
#             sub_dir.isnumeric()
#             or sub_dir == (sub_dir.split("_")[0] + "_ST")
#             or sub_dir == (sub_dir.split("_")[0] + "_GT")
#         )
#         if copy_sub_dir:
#             print(f"复制目录: {sub_dir}")
#             shutil.copytree(raw_data_dir / sub_dir, result_dir / sub_dir)
#         else:
#             print(f"跳过目录: {sub_dir}")
    
#     # 确定要删除的目录类型
#     if keep_st:
#         rm_dir = "_GT"
#         keep_annotation = "_ST"
#     else:
#         rm_dir = "_ST" 
#         keep_annotation = "_GT"
    
#     print(f"删除包含 '{rm_dir}' 的目录，保留包含 '{keep_annotation}' 的目录")
    
#     # 筛选要保留的目录
#     keep_dirs = [sub_dir for sub_dir in os.listdir(result_dir) if rm_dir not in sub_dir]
#     img_dirs = [sub_d for sub_d in keep_dirs if sub_d.isnumeric()]
#     mask_dirs = [sub_d for sub_d in keep_dirs if not sub_d.isnumeric()]
    
#     print(f"图像目录: {img_dirs}")
#     print(f"掩码目录: {mask_dirs}")
    
#     # 排序子目录以避免shutil.move问题
#     keep_dirs = img_dirs + mask_dirs
    
#     # 为每个序列创建目录
#     for sub_dir_name in sub_dir_names:
#         target_dir = result_dir / sub_dir_name
#         if not os.path.exists(target_dir):
#             os.makedirs(target_dir)
#             os.makedirs(target_dir / "images")
#             os.makedirs(target_dir / "masks")
#             print(f"创建目录结构: {target_dir}")
    
#     # 处理每个保留的目录
#     for sub_dir in keep_dirs:
#         sub_dir_name = sub_dir.split("_")[0]
#         print(f"处理目录: {sub_dir} -> 序列: {sub_dir_name}")
        
#         if sub_dir_name not in sub_dir_names:
#             print(f"跳过序列 {sub_dir_name}，不在处理列表中")
#             continue
            
#         assert sub_dir_name.isnumeric(), f"未知的目录命名 {sub_dir}"
        
#         if sub_dir.isnumeric():
#             dir_name = "images"
#             print(f"  处理图像数据: {sub_dir}")
#         else:
#             dir_name = "masks"
#             print(f"  处理掩码数据: {sub_dir}")
            
#             # 检查掩码源目录是否存在
#             source_mask_dir = result_dir / sub_dir
#             if not os.path.exists(source_mask_dir):
#                 print(f"  警告: 掩码源目录不存在: {source_mask_dir}")
#                 continue
            
#             # 列出掩码源目录中的内容
#             mask_contents = os.listdir(source_mask_dir)
#             print(f"  掩码目录内容: {mask_contents}")
            
#             # 如果保留ST，则需要将ST分割注释与GT谱系注释融合
#             if keep_st:
#                 gt_dir = sub_dir.split("_")[0] + "_GT"
#                 gt_path = result_dir / gt_dir
#                 if os.path.exists(gt_path):
#                     print(f"  融合ST和GT注释: {sub_dir} + {gt_dir}")
#                     # 这里调用原来的generate_st_gt_lineage函数
#                     # generate_st_gt_lineage(source_mask_dir / "SEG", gt_path / "TRA")
#                 else:
#                     print(f"  警告: GT目录不存在: {gt_path}")
        
#         # 移动文件到新的目录结构
#         data_path = result_dir / sub_dir_name / dir_name
#         source_path = result_dir / sub_dir
        
#         print(f"  移动 {source_path} -> {data_path}")
        
#         if os.path.exists(source_path):
#             try:
#                 shutil.move(str(source_path), str(data_path))
#                 print(f"  成功移动到: {data_path}")
#             except shutil.Error as e:
#                 print(f"  移动失败，尝试临时目录方法: {e}")
#                 temp = result_dir / "temp"
#                 os.makedirs(str(temp), exist_ok=True)
#                 shutil.move(str(source_path), str(temp))
#                 shutil.move(str(temp), str(data_path))
#                 print(f"  通过临时目录成功移动到: {data_path}")
#         else:
#             print(f"  警告: 源路径不存在: {source_path}")

# def check_data_structure(data_path, sequences):
#     """
#     检查数据结构是否正确
#     """
#     print(f"\n检查数据结构: {data_path}")
    
#     for seq in sequences:
#         train_path = data_path / "train" / seq
        
#         print(f"\n序列 {seq}:")
#         print(f"  训练路径: {train_path}")
        
#         if os.path.exists(train_path):
#             print(f"  训练目录存在")
            
#             images_path = train_path / "images"
#             masks_path = train_path / "masks"
            
#             if os.path.exists(images_path):
#                 image_files = [f for f in os.listdir(images_path) if f.endswith('.tif')]
#                 print(f"  图像文件数量: {len(image_files)}")
#                 if image_files:
#                     print(f"  图像文件示例: {image_files[:3]}")
#             else:
#                 print(f"  警告: 图像目录不存在: {images_path}")
            
#             if os.path.exists(masks_path):
#                 mask_files = [f for f in os.listdir(masks_path) if f.endswith('.tif')]
#                 print(f"  掩码文件数量: {len(mask_files)}")
#                 if mask_files:
#                     print(f"  掩码文件示例: {mask_files[:3]}")
#             else:
#                 print(f"  警告: 掩码目录不存在: {masks_path}")
                
#             # 检查lineage文件
#             lineage_path = train_path / "track.txt"
#             if os.path.exists(lineage_path):
#                 print(f"  lineage文件存在")
#             else:
#                 print(f"  警告: lineage文件不存在: {lineage_path}")
#         else:
#             print(f"  警告: 训练目录不存在: {train_path}")

# # 使用示例
# # if __name__ == "__main__":
# #     # 在运行之前，先检查你的原始数据结构
# #     raw_data_path = Path(r"D:\CodeRode\project\EmbedTrack-master\ctc_raw_data")  # 替换为实际路径
# #     result_path = Path(r"D:\CodeRode\project\EmbedTrack-master\data")   # 替换为实际路径
    
# #     # 检查原始数据
# #     print("原始数据结构:")
# #     if os.path.exists(raw_data_path):
# #         for item in os.listdir(raw_data_path):
# #             print(f"  {item}")
    
# #     # 使用调试版本的函数
# #     debug_copy_and_rename_data(
# #         raw_data_path, 
# #         result_path, 
# #         keep_st=True, 
# #         sub_dir_names=["46"]  # 根据你的实际序列调整
# #     )
# #     # 检查结果
# #     check_data_structure(result_path, ["46"])

# def generate_all_centers(data_root, sub_dir_names, center_type="medoid", crop_size=256):
#     """
#     批量为每个子目录生成center图像。
#     参数：
#         data_root: 数据集根目录（如 Path('data/3t3/train') 或 Path('data/3t3/val')）
#         sub_dir_names: 序列名列表（如["46", "47", ...]）
#         center_type: center类型（如"medoid"、"centroid"等）
#         crop_size: 裁剪尺寸，默认256
#     """
#     from embedtrack.datasets.generate_crops import process
#     from pathlib import Path
#     import os

#     data_root = Path(data_root)
#     for sub_dir in sub_dir_names:
#         seq_path = data_root / sub_dir
#         images_dir = seq_path / "images"
#         masks_dir = seq_path / "masks"
#         center_dir = seq_path / f"center-{center_type}"
#         os.makedirs(center_dir, exist_ok=True)
#         if not images_dir.exists() or not masks_dir.exists():
#             print(f"[WARNING] {seq_path} 缺少 images 或 masks 目录，跳过。")
#             continue
#         image_files = sorted([f for f in os.listdir(images_dir) if f.endswith('.tif')])
#         mask_files = sorted([f for f in os.listdir(masks_dir) if f.endswith('.tif')])
#         for img_file, mask_file in zip(image_files, mask_files):
#             img_path = images_dir / img_file
#             mask_path = masks_dir / mask_file
#             try:
#                 process(str(img_path), str(mask_path), str(seq_path), '', crop_size, center_type, overlap=1.0)
#             except Exception as e:
#                 print(f"[ERROR] 生成center图像失败: {img_path}, {mask_path}, error: {e}")